//
//  Collection+Extensions.swift
//  SFDevFly
//
//  Created by shen on 2023/9/28.
//

import Foundation

public extension Collection {
    /// 是否为空
    var isNotEmpty: Bool { !isEmpty }

    /// 检查是否包含指定索引
    func contains(index: Int) -> Bool {
        return indices.contains(index as! Index)
    }
}

public extension Optional {
    /// 判断是否为空
    var isNil: Bool {
        switch self {
        case .none:
            return true
        case .some:
            return false
        }
    }

    /// 判断是否有值
    var isNotNil: Bool {
        return !isNil
    }

    var isNull: Bool {
        switch self {
        case .none:
            return true
        case .some(let wrapped):
            return wrapped is NSNull
        }
    }
}

public extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        if isNull {
            return true
        }
        switch self {
        case .none:
            return true
        case .some(let wrapped):
            return wrapped.isEmpty
        }
    }

    func emptyOr(_ defaultValue: Wrapped) -> Wrapped {
        if isNull { return defaultValue }
        switch self {
        case .none: return defaultValue
        case .some(let wrapped):
            return wrapped.isEmpty ? defaultValue : wrapped
        }
    }

    func tranformOr(_ defaultValue: Wrapped, tranform: (Wrapped) -> Wrapped) -> Wrapped {
        if isNull { return defaultValue }
        switch self {
        case .none: return defaultValue
        case .some(let wrapped):
            return wrapped.isEmpty ? defaultValue : tranform(wrapped)
        }
    }
}
